
import {  login, loginParam,getUser, userInfoParam } from "/@/api/layout"
import { IUser } from "/@/type/store/user"
import { ActionContext } from 'vuex'
import { getLocal, setLocal, useLocal } from "/@/utils"
import router from "/@/router"
import { IToken } from "/@/type/store/layout"
// 前端检查token是否失效
useLocal('token')
    .then(d => token.ACCESS_TOKEN = d.ACCESS_TOKEN)
    .catch(() => mutations.logout(state))

const token = getLocal<IToken>('token')
const state: IUser = {
    userInfo: {
        id:'',
        token:'',
        name:'',
        permission:[],
    },
    token: {
        ACCESS_TOKEN: token.ACCESS_TOKEN || ''
    },
    wsAdminUrl:'ws://xxxxxx'
}

const mutations = {
    
    login(state: IUser, data:{Token:'',Account:''}):void {
        state.token.ACCESS_TOKEN = data.Token
        setLocal('token', state.token, 10000 * 60 * 60)
        setLocal('userInfo', state.userInfo, 10000 * 60 * 60)
        const { query } = router.currentRoute.value
        router.push(typeof query.from === 'string' ? decodeURIComponent(decodeURIComponent(query.from)) : '/')
    },
    getUser(state: IUser, userInfo:{id:string,token:string,name:string, permission: Array<string>}):void {
        state.userInfo.id = userInfo.id
        state.userInfo.token = userInfo.token
        state.userInfo.name = userInfo.name
        state.userInfo.permission = userInfo.permission
    },
    logout(state: IUser):void {
        state.token.ACCESS_TOKEN = ''
        localStorage.removeItem('token')
        history.go(0)
    },
}


const actions = {
 
    //登录
    async login(context:ActionContext<IUser,IUserState>,params:loginParam):Promise<void>{
        const res = await login(params)
        context.commit('login',res.data.Data)
    },

    // 获取用户详情
    async getUserInfo(context:ActionContext<IUser,IUserState>,params:userInfoParam):Promise<void>{
        const res = await getUser(params)
        const userInfo = res.data.Data
        context.commit('getUser', userInfo)
    },

}

const userState = {
    namespaced: true,
    state,
    mutations,
    actions
}

export default userState
